package org.firebug.spring.boot.exception.handler;

import org.firebug.common.core.api.Meta;
import org.firebug.common.core.api.Response;
import org.springframework.http.HttpStatus;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.LinkedHashMap;
import java.util.Map;

@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * params = {"version=1"}
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {UnsatisfiedServletRequestParameterException.class})
    private Response<Object> handle(UnsatisfiedServletRequestParameterException e) {
        return Response.ng(Meta._400);
    }

    /**
     * @Validated 错误
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    private Response<Object> handle(MethodArgumentNotValidException e) {
        Map<String, String> error = new LinkedHashMap<>();
        Errors errors = e.getBindingResult();
        if (errors.hasErrors()) {
            for (FieldError field : errors.getFieldErrors()) {
                error.put(field.getField(), field.getDefaultMessage());
            }
        }
        return Response.ng(Meta._400, error);
    }

    /**
     * spring.mvc.throw-exception-if-no-handler-found=true
     * spring.resources.add-mappings=false
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(value = {NoHandlerFoundException.class})
    private Response<Object> handle(NoHandlerFoundException e) {
        return Response.ng(Meta._404);
    }

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
    private Response<Object> handle(HttpRequestMethodNotSupportedException e) {
        return Response.ng(Meta._405);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = {Exception.class})
    private Response<Object> handle(Exception e) {
        return Response.ng(Meta._500);
    }
}